/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package maxent.mr.writable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;

/**
 *
 * @author hadoop
 */
public class TagCountWritable implements Writable{

    private HashMap<Text,IntWritable> map = new HashMap();

    public TagCountWritable(){}

    public TagCountWritable(HashMap<Text,IntWritable> map){
        this.map = map;
    }

    private IntWritable getCount(Text tag){
        return map.get(tag);
    }

     @Override
    public String toString() {

        String output = "";
        Text tag = new Text();        

        Iterator<Text> it = map.keySet().iterator();
        while(it.hasNext()){
            tag = it.next();                        
            output += (tag+"=>"+getCount(tag).toString()+" ");            
        }

        return output;

    }

    public void write(DataOutput out) throws IOException {

        Iterator<Text> it = map.keySet().iterator();
        Text tag = new Text();
        IntWritable count = new IntWritable();
        
        while(it.hasNext()){
            tag = it.next();            
            tag.write(out);
            getCount(tag).write(out);
        }
    }

    public void readFields(DataInput in) throws IOException {
        
        Iterator<Text> it = map.keySet().iterator();
        Text tag = new Text();
        IntWritable count = new IntWritable();

        while(it.hasNext()){
            tag = it.next();            
            tag.readFields(in);
            getCount(tag).readFields(in);
        }
        
    }

    

}
